<template>
  <yt-page title="最新通知" scroll>
    <yt-buttonTab :list="pageList" slot="title" @change="tabsChange"></yt-buttonTab>
    <!-- 公告 -->
    <yt-form v-show="page === 0">
      <yt-group :searchApi="searchApiFirst" ref="group0">
        <yt-card slot-scope="scope" :title="scope.bulletin_title" :tag="false" :edge="false">
          <span slot="more">{{ scope.sending_department }}</span>
          <p class="content">{{ scope.bulletin_content }}</p>
          <div class="footer" @click="onDetail(scope)">
            <span>查看信息</span>
          </div>
        </yt-card>
      </yt-group>
    </yt-form>
    <!-- 收发文 -->
    <yt-form v-show="page === 1">
      <yt-group :searchApi="searchApiSecond" ref="group1">
        <yt-card slot-scope="scope" :title="scope.number" :tag="false" :edge="false">
          <span slot="more">{{ scope.sending_department }}</span>
          <p class="content">{{ scope.title }}</p>
          <div class="footer" @click="onDetailFile(scope)">
            <span>查看信息</span>
          </div>
        </yt-card>
      </yt-group>
    </yt-form>
    <!-- 会议 -->
    <yt-form v-show="page === 2">
      <yt-group :searchApi="searchApiThird" ref="group2">
        <yt-card slot-scope="scope" :title="`会议时间：${scope.meeting_start_time}`" :tag="false" :edge="false">
          <span slot="more">{{ scope.sending_department }}</span>
          <p class="content">{{ scope.title }}</p>
          <div class="footer" @click="onDetailMeeting(scope)">
            <span>查看信息</span>
          </div>
        </yt-card>
      </yt-group>
    </yt-form>
  </yt-page>
</template>

<script>
import Router from '@/router'
import { GetStore, Store, JudgeRole } from '@/store'
import { commonApi } from '@/common/api/commonApi.js'
import { ReplaceDictionary } from '@/common/utils/index.js'

export default {
  data() {
    return {
      searchApiFirst: async ({ skip, limit }) => {
        let query = this.getQueryOptions('WJ_notice_bulletin_records', true)
        let options = {
          skip,
          limit,
          include: ['records', 'records_gov'],
          descending: ['createdAt'],
          ...query
        }
        let p = [
          commonApi.dictionary('sending_department'),
          commonApi.search('WJ_notice_bulletin', options)
        ]

        try {
          let [department, data] = await Promise.all(p)
          return ReplaceDictionary(data, { sending_department: department })
        } catch (e) {
          this.handleFetchError(e)
          return []
        }
      },
      searchApiSecond: async ({ skip, limit }) => {
        let query = this.getQueryOptions('WJ_send_files_record')
        let options = {
          skip,
          limit,
          include: ['records', 'records_gov'],
          descending: ['createdAt'],
          ...query
        }
        let p = [
          commonApi.dictionary('sending_department'),
          commonApi.search('WJ_send_files', options)
        ]

        try {
          let [department, data] = await Promise.all(p)
          return ReplaceDictionary(data, { sending_department: department })
        } catch (e) {
          this.handleFetchError(e)
          return []
        }
      },
      searchApiThird: async ({ skip, limit }) => {
        let query = this.getQueryOptions('WJ_conference_record')
        let options = {
          skip,
          limit,
          include: ['records', 'records_gov'],
          descending: ['createdAt'],
          ...query
        }
        let p = [
          commonApi.dictionary('sending_department'),
          commonApi.search('WJ_conference_notice', options)
        ]

        try {
          let [department, data] = await Promise.all(p)
          return ReplaceDictionary(data, { sending_department: department })
        } catch (e) {
          this.handleFetchError(e)
          return []
        }
      },
      page: 0,
      pageList: [{ text: '公告' }, { text: '收发文' }, { text: '会议' }]
    }
  },
  watch: {
    page() {
      setTimeout(() => {
        this.$refs['group' + this.page].startPull()
      }, 30)
    }
  },
  activated() {
    this.initData()
  },
  methods: {
    onDetail(data) {
      let recordId = this.getRecordId(data)
      this.$router.$push({
        path: '/message/detail',
        query: { id: data.id, recordId: recordId }
      })
    },
    onDetailFile(data) {
      let recordId = this.getRecordId(data)
      this.$router.$push({
        path: '/message/detail-file',
        query: { id: data.id, recordId: recordId }
      })
    },
    onDetailMeeting(data) {
      let recordId = this.getRecordId(data)
      this.$router.$push({
        path: '/message/detail-meeting',
        query: { id: data.id, recordId: recordId }
      })
    },
    tabsChange(page) {
      this.page = page
    },
    async initData() {
      let p = [
        commonApi.searchCount(
          'WJ_notice_bulletin',
          this.getQueryOptions('WJ_notice_bulletin_records', true)
        ),
        commonApi.searchCount(
          'WJ_send_files',
          this.getQueryOptions('WJ_send_files_record')
        ),
        commonApi.searchCount(
          'WJ_conference_notice',
          this.getQueryOptions('WJ_conference_record')
        )
      ]
      try {
        let res = await Promise.all(p)
        this.pageList = this.pageList.map((v, index) => ({
          ...v,
          badge: { value: res[index] }
        }))
      } catch (e) {
        this.handleFetchError(e)
      }

    },
    getQueryOptions(collectionName, flag) {
      try {
        let query = JudgeRole()
          .enterprise(() => {
            let id = (GetStore(Store.enterprise) || {}).id
            return {
              matchesQuery: {
                records: commonApi.createQueryIncludeOptions(collectionName, {
                  equalTo: {
                    enterpriseId: id
                  },
                  containedIn: {
                    state: flag ? [0] : [0, 1]
                  }
                })
              }
            }
          })
          .government(() => {
            let id = (GetStore(Store.organization) || {}).id
            return {
              matchesQuery: {
                records_gov: commonApi.createQueryIncludeOptions(collectionName, {
                  equalTo: {
                    gov_org: id
                  },
                  containedIn: {
                    state: flag ? [0] : [0, 1]
                  }
                })
              }
            }
          })
          .default()
        return query
      } catch (e) {
        this.handleFetchError(e)
      }

    },
    getRecordId(data) {
      let recordId = JudgeRole()
        .enterprise(() => {
          let id = (GetStore(Store.enterprise) || {}).id
          let record = data.records.find(
            v => v.attributes.enterpriseId.id === id
          )
          return record ? record.id : ''
        })
        .government(() => {
          let id = (GetStore(Store.organization) || {}).id
          let record = data.records_gov.find(
            v => v.attributes.gov_org.id === id
          )
          return record ? record.id : ''
        })
        .default()
      return recordId
    },
    handleFetchError(e) {
      if (e.code === 119 && e.message === "anonymous  user isn't allowed to perform the find operation.") {
        Router.push({
          path: '/login',
          query: {
            client: 'weixin',
            path: '/message'
          }
        })
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
>>> .yt-group-category
  font-size 16px
  text-align center
  margin-top 15px
.content
  color #666
  font-size 14px
  padding 0 10px
  line-height 26px
.footer
  font-size 14px
  padding 10px 10px 0
  margin-top 10px
  border-top 0.5px solid #f5f5f5
  display flex
  justify-content space-between
  color #03a9f5
</style>
